﻿/************************************************************************
* Copyright (c) 2018 All Rights Reserved.
*命名空间：Common.Standard
*文件名： FileHelper
*创建人： kingling
*创建时间：2018/7/23 13:00:14
*描述
*=======================================================================
*修改标记
*修改时间：2018/7/23 13:00:14
*修改人：kingling
*描述：
************************************************************************/

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http.Headers;
using System.Text;

namespace Common.Standard
{
    public class FileHelper
    {
        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="filedata"></param>
        /// <param name="hostingEnv"></param>
        /// <param name="ratPath"></param>
        /// <returns></returns>
        public static string UploadImage(IFormFile filedata, IHostingEnvironment hostingEnv, string ratPath = "upload")
        {
            var ext = ContentDispositionHeaderValue
                           .Parse(filedata.ContentDisposition)
                           .FileName.ToString()
                           .Trim('"').Split('.')[1].ToLower();

            switch (ext)
            {
                case "jpg":
                case "jpeg":
                case "gif":
                case "png":
                case "bmp":
                    break;
                default:
                    throw new Error("文件格式错误");

            }
            var guid = Guid.NewGuid().ToString("N");
            var fileName = $"{guid}.{ext}";
            var dir = hostingEnv.ContentRootPath + "\\wwwroot\\" + ratPath;
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            var datePath = dir + "\\" + DateTime.Now.ToString("yyyyMMdd");
            if (!Directory.Exists(datePath))
            {
                Directory.CreateDirectory(datePath);
            }
            var path = datePath + "\\" + fileName;
            using (FileStream fs = System.IO.File.Create(path))
            {
                filedata.CopyTo(fs);
                fs.Flush();
            }
            return "/" + ratPath + "/" + DateTime.Now.ToString("yyyyMMdd") + "/" + fileName;
        }
    }
}
